const Router = require('koa-router')
const jwt = require('jsonwebtoken')
const axios = require('axios')
const debug = require('debug')('user')

// 实例化路由
const router = new Router()

// 引入User
const User = require('../../models/User.js')
// 引入config
const ConfigManager = require('../../lib/config.js')
// 引入logger
const logger = require('../../lib/logger.js')
// 引入db
const db = require('../../servse/db.js')

/**
 * @router GET api/users/test
 * @desc 测试接口
 * @access 接口公开
 */
router.post('/test', async ctx => {
  // const name = ctx.request.body.username
  // console.log(name)
  // const psd = ctx.request.body.password
  // console.log(psd)
  // const sql = db1.prepare('insert into File(userName, fileName) values(?,?)', '喊喊', 'sadfdg.pdf')
  // sql.run()
  // ctx.body = '插入成功'
  // return ctx.body
})

/**
 * @router POST api/users/registered
 * @desc 注册接口
 * @access 接口公开
 */
router.post('/registered', async ctx => {
  // console.log(ctx.request.body);
  // 根据email进行数据库查询
  const findResult = await User.find({
    _id: ctx.request.body.id
  })

  // console.log(findResult);
  // 查询有此id
  if (findResult.length > 0) {
    ctx.body = {
      status: 500,
      msg: '用户已存在'
    }
    return ctx.body
  }

  // 新建User对象
  const newUser = new User({
    _id: ctx.request.body.id,
    name: ctx.request.body.name
  })

  // 存储到数据库
  await newUser.save().then(user => {
    ctx.body = user
  }).catch(err => {
    logger.error(err)
    console.log(err)
  })

  // 返回json数据
  ctx.response.body = newUser + '注册成功'
})

/**
 * @router POST api/user/login1
 * @desc 登录接口
 * @access 接口公开
 */
router.post('/login1', async ctx => {
  debug('ctx.body.request.id', ctx.request.body.id)
  // 查询
  const findResult = await db.findUserId(ctx.request.body.id)
  console.log('Userinfo: ', findResult[0])

  if (findResult === 0) {
    ctx.status = 404
    ctx.body = '用户不存在'
  } else {
    // 获取查询到的用户
    const user = findResult[0]
    // 验证密码
    // let result = await bcrypt.compareSync(ctx.request.body.password, user.password);
    if (user) {
      // 验证通过，对称加密生成并返回token
      const payload = {
        id: user.id,
        name: user.name,
        // 设置过期时间
        exp: Math.floor(Date.now() / 1000) + 3600
      }
      const token = jwt.sign(payload, ConfigManager.getSecretKey())

      ctx.status = 200
      ctx.body = {
        msg: '登录成功',
        token: token
      }
    } else {
      ctx.status = 400
      ctx.body = '密码错误'
    }
  }
})

/**
 * @router POST api/user/login
 * @desc 对接前端小程序登录接口
 * @access 接口公开
 */
router.post('/login', async ctx => {
  const code = ctx.request.body.code
  const appID = ConfigManager.getAppid()
  const appSecret = ConfigManager.getAppSecret()

  // 获取openid跟session_key
  const { data } = await axios.get('https://api.weixin.qq.com/sns/jscode2session?appid=' + appID + '&secret=' + appSecret + '&js_code=' + code + '&grant_type=authorization_code', {})
  if (data.errcode) {
    debug('error:', data.errmsg)
  }
  debug('userinfo', data)

  const findResult = await db.findUserId(data.openid)
  debug('Userinfo: ', findResult[0])

  if (findResult.length === 0) {
    // 新建User对象
    const newUser = new User({
      id: data.openid,
      name: ctx.request.body.data.nickName,
      avatar: ctx.request.body.data.avatarUrl
    })

    // 存储到数据库
    await db.savaUser(newUser)

    // 验证通过，对称加密生成并返回token
    const payload = {
      id: data.openid,
      name: newUser.name,
      exp: Math.floor(Date.now() / 1000) + 1209600
    }
    const token = jwt.sign(payload, ConfigManager.getSecretKey())

    ctx.status = 200
    ctx.body = {
      errcode: 0,
      errmsg: '登录成功',
      data: {
        token: token
      }
    }
    return ctx.body
  }

  // 获取查询到的用户
  const user = findResult[0]
  if (user) {
    // 验证通过，对称加密生成并返回token
    const payload = {
      id: user.id,
      name: user.name,
      exp: Math.floor(Date.now() / 1000) + 1209600
    }
    const token = jwt.sign(payload, ConfigManager.getSecretKey())

    ctx.status = 200
    ctx.body = {
      errcode: 0,
      errmsg: '登录成功',
      data: {
        token: token
      }
    }
    return ctx.body
  }
})

module.exports = router.routes()
